package com.beone.admin.security.handler;

import com.base.common.RequestContextUtils;
import com.beone.admin.entity.SysLog;
import com.beone.admin.security.SysUser;
import com.beone.admin.service.SysLogService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

/**
 * @title
 * @Author 覃球球
 * @Version 1.0 on 2017/12/22.
 * @Copyright 长笛龙吟
 */
public class SimpleLoginSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    private Logger logger = LoggerFactory.getLogger(SimpleLoginSuccessHandler.class);

    private SysLogService sysLogService;

    public void setSysLogService(SysLogService sysLogService) {
        this.sysLogService = sysLogService;
    }

    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response
            , Authentication authentication) throws IOException, ServletException {
        SysLog log = new SysLog();
        log.setCreateTime(new Date());
        log.setType("LOGIN");
        log.setContent("登录成功!");
        log.setIp(RequestContextUtils.getClientIp(request));
        SysUser currentUser = (SysUser) authentication.getPrincipal();
        if(currentUser != null){
            log.setUsername(currentUser.getUsername());
        }
        sysLogService.insert(log);

//        super.onAuthenticationSuccess(request, response, authentication);
        // 解决session丢失后，重新登录跳转上一次访问的页面，登录后直接重定向到index
        clearAuthenticationAttributes(request);
        String targetUrl = determineTargetUrl(request, response);
        getRedirectStrategy().sendRedirect(request, response, targetUrl);
        logger.info("login success handler ................");
    }
}
